<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1" name="viewport">
    <title>我的电视</title>
    <!-- 重置css -->
    <link href="https://cdn.jsdelivr.net/npm/@unocss/reset/tailwind.min.css" rel="stylesheet">

    <!-- 核心 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@3.4.23/dist/vue.global.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@unocss/runtime"></script>

    <!-- 日期格式化 -->
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/locale/zh-cn.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/relativeTime.js"></script>

    <!-- vant -->
    <link href="https://fastly.jsdelivr.net/npm/vant@4/lib/index.css" rel="stylesheet" />
    <script src="https://fastly.jsdelivr.net/npm/vant@4/lib/vant.min.js"></script>

    <!-- 工具 -->
    <script src="https://cdn.jsdelivr.net/npm/humanize-duration@3.32.0/humanize-duration.min.js"></script>

    <style>
        .van-theme-dark body {
            color: #f5f5f5;
            background-color: black;
        }
    </style>
</head>

<body>
    <div class="min-h-100vh py-46px" id="app">
        <van-config-provider :theme="isDark ? 'dark' : undefined">
            <template v-if="settings">
                <div class="p-20px pt-0">
                    <div class="ml-16px text-32px">{{ settings.appTitle }}</div>
                    <div class="ml-16px text-gray text-14px">{{ settings.appRepo }}</div>
                </div>

                <van-cell-group inset title="通知">
                    <van-cell title="修改之前请先关闭应用的设置界面，否则会有冲突"></van-cell>
                    <van-cell title="以下设置修改后，需要重启应用生效"></van-cell>
                </van-cell-group>

                <van-cell-group inset title="应用">
                    <van-cell label="需要在设备系统进行设置" title="开机自启">
                        <template #extra>
                            <van-switch @change="confirmSettings" size="24" v-model="settings.appBootLaunch" />
                        </template>
                    </van-cell>
                </van-cell-group>

                <van-cell-group inset title="直播源">
                    <van-cell :label="settings.iptvChannelChangeFlip ? '方向键上：下一个频道；方向键下：上一个频道': '方向键上：上一个频道；方向键下：下一个频道'"
                        title="换台反转">
                        <template #extra>
                            <van-switch @change="confirmSettings" size="24" v-model="settings.iptvChannelChangeFlip" />
                        </template>
                    </van-cell>

                    <van-cell title="自定义直播源">
                        <template #label>
                            <van-space class="w-full" direction="vertical" size="small">
                                <span>支持m3u链接与tvbox链接</span>
                                <span>不支持多源，若存在多源只会选择第一个播放地址，其他忽略
                                </span>
                                <van-field class="!p-0" placeholder="置为空时，将恢复默认"
                                    v-model="settings.iptvSourceUrl"></van-field>
                            </van-space>
                        </template>

                        <template #extra>
                            <van-button @click="settings.iptvSourceCachedAt = 0; confirmSettings()" size="small"
                                type="primary">推送链接
                            </van-button>
                        </template>
                    </van-cell>

                    <van-cell title="直播源精简">
                        <template #label>
                            <van-space direction="vertical" size="small">
                                <span>{{ settings.iptvSourceSimplify ? '显示精简直播源(仅央视、地方卫视)':
                                    '显示完整直播源' }}
                                </span>
                                <span>{{ settings.iptvSourceSimplify ?
                                    '精简规则：频道名称以·CCTV·开头或以·卫视·结尾'
                                    : '' }}
                                </span>
                            </van-space>
                        </template>

                        <template #extra>
                            <van-switch @change="confirmSettings" size="24" v-model="settings.iptvSourceSimplify" />
                        </template>
                    </van-cell>

                    <van-cell title="直播源缓存">
                        <template #label>
                            {{ settings.iptvSourceCachedAt > 0 ? `缓存于
                            ${dayjs(settings.iptvSourceCachedAt).fromNow()}` : '未缓存' }}
                        </template>

                        <template #extra>
                            <van-button @click="settings.iptvSourceCachedAt = 0; confirmSettings()" size="small"
                                type="warning">清除缓存
                            </van-button>
                        </template>
                    </van-cell>

                    <van-cell title="直播源缓存时间">
                        <template #label>
                            {{ foramtDuration(settings.iptvSourceCacheTime) }}
                        </template>

                        <template #extra>
                            <van-space>
                                小时
                                <van-stepper :min="0" :model-value="settings.iptvSourceCacheTime / 1000 / 60 / 60"
                                    @change="confirmSettings()"
                                    @update:model-value="settings.iptvSourceCacheTime = $event * 1000 * 60 * 60"></van-stepper>
                            </van-space>
                        </template>
                    </van-cell>
                </van-cell-group>

                <van-cell-group inset title="节目单">
                    <van-cell label="在低端设备上，首次加载时可能会有跳帧风险" title="节目单启用">
                        <template #extra>
                            <van-switch @change="confirmSettings" size="24" v-model="settings.epgEnable" />
                        </template>
                    </van-cell>

                    <van-cell title="自定义节目单">
                        <template #label>
                            <van-field class="!p-0" placeholder="置为空时，将恢复默认" v-model="settings.epgXmlUrl"></van-field>
                        </template>

                        <template #extra>
                            <van-button
                                @click="settings.epgXmlCachedAt = 0; settings.epgCachedHash = 0; confirmSettings()"
                                size="small" type="primary">推送链接
                            </van-button>
                        </template>
                    </van-cell>

                    <van-cell title="节目单缓存">
                        <template #label>
                            {{ settings.epgXmlCachedAt > 0 ? `缓存于
                            ${dayjs(settings.epgXmlCachedAt).fromNow()}` : '未缓存' }}
                        </template>

                        <template #extra>
                            <van-button
                                @click="settings.epgXmlCachedAt = 0; settings.epgCachedHash = 0; confirmSettings()"
                                size="small" type="warning">
                                清除缓存
                            </van-button>
                        </template>
                    </van-cell>

                    <van-cell title="节目单刷新时间阈值">
                        <template #label>
                            在{{ settings.epgRefreshTimeThreshold }}点之前，不会获取节目单
                        </template>

                        <template #extra>
                            <van-space>
                                小时
                                <van-stepper @change="confirmSettings()" integer
                                    v-model="settings.epgRefreshTimeThreshold"></van-stepper>
                            </van-space>
                        </template>
                    </van-cell>
                </van-cell-group>

                <van-cell-group inset title="界面">
                    <van-cell label="在频道项底部显示当前节目进度条" title="显示节目进度">
                        <template #extra>
                            <van-switch @change="confirmSettings" size="24"
                                v-model="settings.uiShowEpgProgrammeProgress" />
                        </template>
                    </van-cell>
                </van-cell-group>

                <van-cell-group inset title="调试">
                    <van-cell label="在屏幕左上角显示fps和柱状图" title="显示fps">
                        <template #extra>
                            <van-switch @change="confirmSettings" size="24" v-model="settings.debugShowFps" />
                        </template>
                    </van-cell>

                    <van-cell label="显示播放器详细信息（编码、解码器、采样率等）" title="显示播放器信息">
                        <template #extra>
                            <van-switch @change="confirmSettings" size="24" v-model="settings.debugShowPlayerInfo" />
                        </template>
                    </van-cell>

                    <van-cell title="上传apk">
                        <template #extra>
                            <van-uploader :after-read="uploaderAfterRead" accept=".apk" />
                        </template>
                    </van-cell>
                </van-cell-group>

                <!-- <van-tabbar>
                        <van-tabbar-item name="home" icon="tv-o">直播源</van-tabbar-item>
                        <van-tabbar-item name="search" icon="list-switch">节目单</van-tabbar-item>
                        <van-tabbar-item name="friends" icon="brush-o">界面</van-tabbar-item>
                        <van-tabbar-item name="setting" icon="setting-o">应用</van-tabbar-item>
                        <van-tabbar-item name="setting" icon="bulb-o">调试</van-tabbar-item>
                    </van-tabbar> -->
            </template>

            <van-empty image="network" v-else />
        </van-config-provider>
    </div>

    <script>
        const { createApp, ref, onMounted, watch, nextTick } = Vue

        const baseUrl = ""

        async function requestApi(url, config) {
            const resp = await fetch(`${baseUrl}${url}`, config)
            if (resp.status !== 200) {
                throw new Error(`请求失败：${resp.status}`)
            }

            return resp
        }

        dayjs.locale('zh-cn')
        dayjs.extend(dayjs_plugin_relativeTime)

        createApp({
            setup() {
                const isDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

                const tabActive = ref(0)

                const settings = ref()
                async function confirmSettings() {
                    try {
                        vant.showLoadingToast({ message: '加载中...', forbidClick: true, duration: 0 })
                        await requestApi('/api/settings', {
                            method: "POST",
                            body: JSON.stringify(settings.value),
                            headers: { 'Content-Type': 'application/json' }
                        })
                        await refreshSettings()
                        vant.closeToast()
                    } catch (e) {
                        vant.showFailToast('无法修改设置')
                        console.error(e)
                        refreshSettings()
                    }
                }
                async function refreshSettings() {
                    try {
                        vant.showLoadingToast({ message: '加载中...', forbidClick: true, duration: 0 })
                        settings.value = await (await requestApi('/api/settings')).json()
                        vant.closeToast()
                    } catch (e) {
                        vant.showFailToast('无法获取设置')
                        console.error(e)
                    }
                }


                onMounted(async () => {
                    await refreshSettings()
                })

                function foramtDuration(ms) {
                    return humanizeDuration(ms, { language: 'zh_CN', round: true, largest: 2 })
                }

                async function uploaderAfterRead(file) {
                    try {
                        vant.showLoadingToast({ message: '加载中...', forbidClick: true, duration: 0 })
                        const formData = new FormData()
                        formData.append('filename', file.file)
                        await requestApi('/api/upload/apk', { method: "POST", body: formData })
                        vant.closeToast()
                    } catch (e) {
                        vant.showFailToast('上传apk失败')
                        console.error(e)
                    }
                }

                return {
                    dayjs,
                    foramtDuration,
                    isDark,
                    tabActive,
                    settings,
                    confirmSettings,
                    uploaderAfterRead,
                }
            }
        })
            .use(vant)
            .mount('#app')
    </script>
</body>

</html>
